package com.funeral.diyaccount.backstage.menu.util;

import com.funeral.diyaccount.backstage.menu.entity.TDAMenu;
import com.funeral.diyaccount.backstage.menu.vo.easyui.MenuTreegridVO;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsDateJsonValueProcessor;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by peizangpin on 2017/5/22.
 */
public class MenuUtils {

    public static List<MenuTreegridVO> changeToMenuTreegridVOList(Collection<TDAMenu> menus)throws InvocationTargetException, IllegalAccessException{
        if(menus == null){
            return null;
        }
        List<MenuTreegridVO> voList = new ArrayList<MenuTreegridVO>();
        for(TDAMenu menu:menus){
            voList.add(MenuUtils.changeToMenuTreegridVO(menu));
        }
        return voList;
    }

    public static MenuTreegridVO changeToMenuTreegridVO(TDAMenu menu) throws InvocationTargetException, IllegalAccessException {
        if(menu == null){
            return null;
        }
        MenuTreegridVO vo = new MenuTreegridVO();
        BeanUtils.copyProperties(menu,vo);
        vo.set_parentId(vo.getParentid());
        if(vo.getMenuFolder() == 1){
            vo.setState("closed");
        }
        return vo;
    }

    public static JsonConfig getJSONConfig(){
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        jsonConfig.registerJsonValueProcessor(java.sql.Date.class,new JsDateJsonValueProcessor());
        jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String key, Object value) {
                //针对_parentId字段的输出过滤
                if(key.equals("_parentId") && ( new Long(0L).equals(value) || value == null)){
                    return true;
                }
                return false;
            }
        });

        return jsonConfig;
    }

}
